package com.lee.init.service.impl;

import com.lee.init.entity.TranMissCredit;
import com.lee.init.entity.TranMissCreditLog;
import com.lee.init.entity.TranMissIntegrationLog;
import com.lee.init.mapper.TranMissCreditLogMapper;
import com.lee.init.mapper.TranMissCreditMapper;
import com.lee.init.mapper.TranMissIntegrationLogMapper;
import com.lee.init.service.IDepositService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class DepositServiceImpl implements IDepositService {

    @Autowired
    private TranMissCreditMapper creditMapper;
    @Autowired
    private TranMissCreditLogMapper creditLogMapper;
    @Autowired
    private TranMissIntegrationLogMapper integrationLogMapper;

    /**
     * 存款
     * 引入积分之前的处理
     * @param loginName
     * @param amount
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TranMissCredit deposit(String loginName, BigDecimal amount) {
        TranMissCredit credit = creditMapper.getByLoginName(loginName);
        BigDecimal creditAfter = credit.getCredit().add(amount);

        TranMissCreditLog creditLog = new TranMissCreditLog(loginName, credit.getCredit(),
                amount, creditAfter, "充值: " + amount);
        credit.setCredit(creditAfter);

        creditMapper.update(credit);
        creditLogMapper.insert(creditLog);

        return credit;
    }

    /**
     * 存款
     * 引入积分后的新增的方法
     * @param loginName
     * @param amount
     * @param integration
     * @return
     */
    @Override
    public TranMissCredit deposit(String loginName, BigDecimal amount, int integration) {
        TranMissCredit credit = deposit(loginName, amount);             // 复用之前的存款逻辑

        // 下面是新增的积分业务
        int integrationAfter = credit.getIntegration() + integration;
        TranMissIntegrationLog log = new TranMissIntegrationLog(loginName, credit.getIntegration(),
                integration, integrationAfter, "充值赠送积分: " + integration);
        credit.setIntegration(integrationAfter);

        creditMapper.update(credit);
        integrationLogMapper.insert(log);
        return credit;
    }
}
